<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
    

    

    



    <meta charset="utf-8">
    
    
    <meta name="sogou_site_verification" content="true">
    
    
    
    <title>用Redis实现接口限流 | Lvshen&#39;s Blog | This is My World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="Redis,限流">
    <meta name="baidu-site-verification" content="VIVNdSiMZm">
    <meta name="description" content="为什么需要限流在高并发环境下，为了缓解数据库，服务器的压力，往往需要对一些接口进行限制操作。比如某个接口10s内只能调用5次，需要怎么做呢？ 这里我有一个思路，利用Redis的incr命令，每次调用接口，原子自增 +1，当自增的值大于设定的次数时，就不让调用接口（返回接口调用次数已经用完之类的）。 Lua脚本Lua脚本的多个命令操作可以实现原子性，下面为相关的Lua脚本命令。">
<meta name="keywords" content="Redis,限流">
<meta property="og:type" content="article">
<meta property="og:title" content="用Redis实现接口限流">
<meta property="og:url" content="https://lvshen9.gitee.io/2020/04/25/1/index.html">
<meta property="og:site_name" content="Lvshen&#39;s Blog">
<meta property="og:description" content="为什么需要限流在高并发环境下，为了缓解数据库，服务器的压力，往往需要对一些接口进行限制操作。比如某个接口10s内只能调用5次，需要怎么做呢？ 这里我有一个思路，利用Redis的incr命令，每次调用接口，原子自增 +1，当自增的值大于设定的次数时，就不让调用接口（返回接口调用次数已经用完之类的）。 Lua脚本Lua脚本的多个命令操作可以实现原子性，下面为相关的Lua脚本命令。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://s1.ax1x.com/2020/04/25/JyokRK.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/04/25/Jyo9aR.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/04/25/JyoAxO.png">
<meta property="og:updated_time" content="2020-04-25T13:18:45.646Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="用Redis实现接口限流">
<meta name="twitter:description" content="为什么需要限流在高并发环境下，为了缓解数据库，服务器的压力，往往需要对一些接口进行限制操作。比如某个接口10s内只能调用5次，需要怎么做呢？ 这里我有一个思路，利用Redis的incr命令，每次调用接口，原子自增 +1，当自增的值大于设定的次数时，就不让调用接口（返回接口调用次数已经用完之类的）。 Lua脚本Lua脚本的多个命令操作可以实现原子性，下面为相关的Lua脚本命令。">
<meta name="twitter:image" content="https://s1.ax1x.com/2020/04/25/JyokRK.png">
    
    <link rel="shortcut icon" href="/img/mylogo.jpg">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">我的技术小房间</h5>
          <a href="mailto:https://lvshen9.github.io" title="https://lvshen9.github.io" class="mail">https://lvshen9.github.io</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/about"  >
                <i class="icon icon-lg icon-address-book"></i>
                About
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/collection"  >
                <i class="icon icon-lg icon-apple"></i>
                Collection
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://lvshen9.github.io/" target="_blank" >
                <i class="icon icon-lg icon-wordpress"></i>
                Blog
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/lvshen9" target="_blank" >
                <i class="icon icon-lg icon-github-alt"></i>
                GitHub
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">用Redis实现接口限流</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">用Redis实现接口限流</h1>
        <h5 class="subtitle">
            
                <time datetime="2020-04-25T11:45:35.000Z" itemprop="datePublished" class="page-time">
  2020-04-25
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术/">技术</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#为什么需要限流"><span class="post-toc-number">1.</span> <span class="post-toc-text">为什么需要限流</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#Lua脚本"><span class="post-toc-number">2.</span> <span class="post-toc-text">Lua脚本</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#限流注解"><span class="post-toc-number">3.</span> <span class="post-toc-text">限流注解</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#AOP编程"><span class="post-toc-number">4.</span> <span class="post-toc-text">AOP编程</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#测试Controller"><span class="post-toc-number">5.</span> <span class="post-toc-text">测试Controller</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#测试结果"><span class="post-toc-number">6.</span> <span class="post-toc-text">测试结果</span></a></li></ol>
        </nav>
    </aside>


<article id="post-1"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">用Redis实现接口限流</h1>
        <div class="post-meta">
            <time class="post-time" title="2020-04-25 19:45:35" datetime="2020-04-25T11:45:35.000Z"  itemprop="datePublished">2020-04-25</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/技术/">技术</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h4 id="为什么需要限流"><a href="#为什么需要限流" class="headerlink" title="为什么需要限流"></a>为什么需要限流</h4><p>在高并发环境下，为了缓解数据库，服务器的压力，往往需要对一些接口进行限制操作。比如某个接口<code>10s</code>内只能调用<code>5</code>次，需要怎么做呢？</p>
<p>这里我有一个思路，利用<code>Redis</code>的<code>incr</code>命令，每次调用接口，原子自增 <code>+1</code>，当自增的值大于设定的次数时，就不让调用接口（返回接口调用次数已经用完之类的）。</p>
<h4 id="Lua脚本"><a href="#Lua脚本" class="headerlink" title="Lua脚本"></a>Lua脚本</h4><p><code>Lua</code>脚本的多个命令操作可以实现原子性，下面为相关的<code>Lua</code>脚本命令。</p>
<a id="more"></a>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">--获取key</span><br><span class="line">local key1 = KEYS[1]</span><br><span class="line"></span><br><span class="line">--原子自增操作</span><br><span class="line">local val = redis.call('incr',key1)</span><br><span class="line"></span><br><span class="line">--返回key的剩余生存时间</span><br><span class="line">local ttl = redis.call('ttl',key1)</span><br><span class="line"></span><br><span class="line">--获取java代码中的参数</span><br><span class="line">--(Long) redisTemplate.execute(getRedisScript, keyList, expireTimes, limitTimes);</span><br><span class="line">local expire = ARGV[1]</span><br><span class="line">local times = ARGV[2]</span><br><span class="line"></span><br><span class="line">--日志打印</span><br><span class="line">redis.log(redis.LOG_DEBUG,tostring(times))</span><br><span class="line">redis.log(redis.LOG_DEBUG,tostring(expire))</span><br><span class="line"></span><br><span class="line">redis.log(redis.LOG_NOTICE, "incr "..key1.."  "..val);</span><br><span class="line"></span><br><span class="line">--给指定的key设置生存时间</span><br><span class="line">if val == 1 then</span><br><span class="line">    redis.call('expire',key1,tonumber(expire))</span><br><span class="line">else</span><br><span class="line">   if ttl == -1 then</span><br><span class="line">       redis.call('expire', key1, tonumber(expire))</span><br><span class="line">   end</span><br><span class="line">end</span><br><span class="line"></span><br><span class="line">--超过限制次数，返回false</span><br><span class="line">if val &gt; tonumber(times) then</span><br><span class="line">   return 0</span><br><span class="line">end</span><br><span class="line"></span><br><span class="line">return 1</span><br></pre></td></tr></table></figure>
<h4 id="限流注解"><a href="#限流注解" class="headerlink" title="限流注解"></a>限流注解</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(ElementType.METHOD)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> RateLimiter &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 限流key</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">String <span class="title">key</span><span class="params">()</span> <span class="keyword">default</span> "rate:limiter"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 单位时间限制通过的请求数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">long</span> <span class="title">limit</span><span class="params">()</span> <span class="keyword">default</span> 10</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 过期时间，单位s</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">long</span> <span class="title">expire</span><span class="params">()</span> <span class="keyword">default</span> 1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 提示</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">String <span class="title">message</span><span class="params">()</span> <span class="keyword">default</span> "<span class="keyword">false</span>"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="AOP编程"><a href="#AOP编程" class="headerlink" title="AOP编程"></a>AOP编程</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Aspect</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RateLimiterHandler</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RedisTemplate redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> DefaultRedisScript&lt;Long&gt; getRedisScript;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostConstruct</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        getRedisScript = <span class="keyword">new</span> DefaultRedisScript&lt;&gt;();</span><br><span class="line">        getRedisScript.setResultType(Long<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        getRedisScript.setScriptSource(<span class="keyword">new</span> ResourceScriptSource(<span class="keyword">new</span> ClassPathResource(<span class="string">"rateLimiter.lua"</span>)));</span><br><span class="line">        log.info(<span class="string">"&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;RateLimiterHandler[分布式限流处理器] lua脚本加载完成"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Pointcut</span>(<span class="string">"@annotation(com.lvshen.demo.redis.ratelimiter.RateLimiter)"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">rateLimiter</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Around</span>(<span class="string">"rateLimiter()"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">around</span><span class="params">(ProceedingJoinPoint point)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        log.info(<span class="string">"&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;RateLimiterHandler[分布式限流处理器]开始执行限流操作"</span>);</span><br><span class="line">        <span class="comment">/*Signature signature = point.getSignature();</span></span><br><span class="line"><span class="comment">        if (!(signature instanceof MethodSignature)) &#123;</span></span><br><span class="line"><span class="comment">            throw new IllegalArgumentException("the Annotation @RateLimiter must used on method!");</span></span><br><span class="line"><span class="comment">        &#125;*/</span></span><br><span class="line">        MethodSignature signature = (MethodSignature) point.getSignature();</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 获取注解参数</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        Method method = point.getTarget().getClass().getMethod(signature.getName(), signature.getMethod().getParameterTypes());</span><br><span class="line">        RateLimiter rateLimiter = method.getAnnotation(RateLimiter<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line"></span><br><span class="line">        String limitKey = rateLimiter.key();</span><br><span class="line">        Preconditions.checkNotNull(limitKey);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> limitTimes = rateLimiter.limit();</span><br><span class="line">        <span class="keyword">long</span> expireTimes = rateLimiter.expire();</span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;RateLimiterHandler[分布式限流处理器]参数值为-limitTimes=&#123;&#125;,limitTimeout=&#123;&#125;"</span>, limitTimes, expireTimes);</span><br><span class="line">        String message = rateLimiter.message();</span><br><span class="line">        <span class="keyword">if</span> (StringUtils.isBlank(message)) &#123;</span><br><span class="line">            message = <span class="string">"false"</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//执行lua脚本</span></span><br><span class="line">        List&lt;String&gt; keyList = Lists.newArrayList();</span><br><span class="line">        keyList.add(limitKey);</span><br><span class="line"></span><br><span class="line">        Long result = (Long) redisTemplate.execute(getRedisScript, keyList, expireTimes, limitTimes);</span><br><span class="line"></span><br><span class="line">        StringBuffer sb = <span class="keyword">new</span> StringBuffer();</span><br><span class="line">        <span class="keyword">if</span> ((result == <span class="number">0</span>)) &#123;</span><br><span class="line">            String msg = sb.append(<span class="string">"超过单位时间="</span>).append(expireTimes).append(<span class="string">"允许的请求次数="</span>).append(limitTimes).append(<span class="string">"[触发限流]"</span>).toString();</span><br><span class="line">            log.info(msg);</span><br><span class="line">            <span class="keyword">return</span> message;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//执行远方法</span></span><br><span class="line">        <span class="keyword">return</span> point.proceed();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="测试Controller"><a href="#测试Controller" class="headerlink" title="测试Controller"></a>测试Controller</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestLimiterController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String MESSAGE = <span class="string">"&#123;\"code\":\"400\",\"msg\":\"FAIL\",\"desc\":\"触发限流\"&#125;"</span>;</span><br><span class="line"></span><br><span class="line">    AtomicInteger atomicInteger = <span class="keyword">new</span> AtomicInteger();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 10s限制请求5次</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> request</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(<span class="string">"ratelimiter"</span>)</span><br><span class="line">    <span class="meta">@RateLimiter</span>(key = <span class="string">"ratedemo:1"</span>, limit = <span class="number">5</span>, expire = <span class="number">10</span>, message = MESSAGE)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">test</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> count = atomicInteger.incrementAndGet();</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"正常请求"</span> + count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="测试结果"><a href="#测试结果" class="headerlink" title="测试结果"></a>测试结果</h4><p>用<code>postman</code>测试</p>
<p>请求第一次</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/04/25/JyokRK.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<p>…</p>
<p>请求第五次</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/04/25/Jyo9aR.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<p>当请求第六次时，出发限流</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://s1.ax1x.com/2020/04/25/JyoAxO.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<p>这只是简单的限流设计，实际使用可能还需要考虑好很多方面。不过现在<code>Redis4.0</code>提供了一个<code>Redis</code>限流模块，<code>Redis-Cell</code>，该模块使用了<code>漏斗算法</code>。并提供了原子的限流指令。有兴趣的可以自行研究下。</p>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-04-25T13:18:45.646Z" itemprop="dateUpdated">2020-04-25 21:18:45</time>
</span><br>


        
        原文链接：<a href="/2020/04/25/1/" target="_blank" rel="external">https://lvshen9.gitee.io/2020/04/25/1/</a>
        
    </div>
    
    <footer>
        <a href="https://lvshen9.gitee.io">
            <img src="/img/avatar.jpg" alt="我的技术小房间">
            我的技术小房间
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Redis/">Redis</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/限流/">限流</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://lvshen9.gitee.io/2020/04/25/1/&title=《用Redis实现接口限流》 — Lvshen's Blog&pic=https://lvshen9.gitee.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://lvshen9.gitee.io/2020/04/25/1/&title=《用Redis实现接口限流》 — Lvshen's Blog&source=为什么需要限流在高并发环境下，为了缓解数据库，服务器的压力，往往需要对一些接口进行限制操作。比如某个接口10s内只能调用5次，需要怎么做呢？
这里我有一个..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://lvshen9.gitee.io/2020/04/25/1/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《用Redis实现接口限流》 — Lvshen's Blog&url=https://lvshen9.gitee.io/2020/04/25/1/&via=https://lvshen9.gitee.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://lvshen9.gitee.io/2020/04/25/1/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2020/04/27/1/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">阿里多线程面试题-按线程顺序输出</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2020/04/23/1/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Redis实现延迟队列</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail,link'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'false' == 'true',
            appId: "dy9kXHwg5jQUlLryQmpjWRlM-gzGzoHsz",
            appKey: "P9Nh39Ol0JbMMiYqNGHEP3ml",
            avatar: "mm",
            placeholder: "Just go go",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="https://lvshen9.github.io/blog2/pay/weixin.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="https://lvshen9.github.io/blog2/pay/weixin.jpg" data-alipay="https://lvshen9.github.io/blog2/pay/zhifu.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>我的技术小房间 &copy; 2015 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://lvshen9.gitee.io/2020/04/25/1/&title=《用Redis实现接口限流》 — Lvshen's Blog&pic=https://lvshen9.gitee.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://lvshen9.gitee.io/2020/04/25/1/&title=《用Redis实现接口限流》 — Lvshen's Blog&source=为什么需要限流在高并发环境下，为了缓解数据库，服务器的压力，往往需要对一些接口进行限制操作。比如某个接口10s内只能调用5次，需要怎么做呢？
这里我有一个..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://lvshen9.gitee.io/2020/04/25/1/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《用Redis实现接口限流》 — Lvshen's Blog&url=https://lvshen9.gitee.io/2020/04/25/1/&via=https://lvshen9.gitee.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://lvshen9.gitee.io/2020/04/25/1/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=https://lvshen9.gitee.io/2020/04/25/1/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
